<?php
/**
 * Created by PhpStorm.
 * User: 丶晓
 * Date: 2017/8/11
 * Time: 10:21
 */

namespace app\api\service;

use app\api\controller\Open;
use app\common\Base;
use think\Config;
use app\api\model\BindModel;
use app\common\Wechat\WechatSDK;

class WechatService extends Base
{
    /*
     * 验证是否来自微信服务器
     * @parm 丶晓
     * $get : signature , timestamp , nonce
     */
    public function vailCallBack($get)
    {
        $signature = $get["signature"];
        $timestamp = $get["timestamp"];
        $nonce = $get["nonce"];

        $tmpArr = [Config::get('wechat.mp_token'), $timestamp, $nonce];
        sort($tmpArr);
        $tmpStr1 = implode($tmpArr);
        $tmpStr = sha1($tmpStr1);
        if ($tmpStr == $signature) {
            return true;
        }
        return false;
    }

    /*
     * 事件处理器
     */
    public function Event($obj)
    {
        switch ($obj->Event) {
            case 'SCAN':
                /*
                 * 扫描二维码事件 (:TYPE)[:VALUE]
                 */
                $openId = $obj->FromUserName;
                $Key = $obj->EventKey;
                $type = getNeedBetween($Key, '(', ')');
                $data = getNeedBetween($Key, '[', ']');
                switch ($type) {
                    case 'setWXCallBack':
                        // bindMiniAppId
                        $M = new BindModel();
                        if ($M->changeInfo('BindMiniAppId', ['miniID' => $data, 'openID' => $openId])) {
                            $appName = $M->seleteInfo('appName', ['miniID' => $data]);
                            return $this->responseText($obj, '已开启"' . $appName . '"小程序通知功能 ^_^');
                        }
                        return false;
                        break;
                    default:
                        return '';
                        break;
                }
                break;
            case 'subscribe':
                /*
                 * 关注事件 (:TYPE)[:VALUE]
                 */
                $openId = $obj->FromUserName;
                $Key = $obj->EventKey;
                $type = getNeedBetween($Key, '(', ')');
                $data = getNeedBetween($Key, '[', ']');
                switch ($type) {
                    case 'setWXCallBack':
                        // bindMiniAppId
                        $M = new BindModel();
                        if ($M->changeInfo('BindMiniAppId', ['miniID' => $data, 'openID' => $openId])) {
                            $appName = $M->seleteInfo('appName', ['miniID' => $data]);
                            return $this->responseText($obj, '已开启"' . $appName . '"小程序通知功能 ^_^');
                        }
                        return false;
                        break;
                    default:
                        return '';
                        break;
                }
                break;
            case 'TEMPLATESENDJOBFINISH':
                /*
                 * 模板消息发送后触发事件
                 */
                return '';
                break;
        }
        return null;
    }

    /*
     * 文字消息回复
     * $parm XML : As : Array
     */

    private function responseText($postObj, $content)
    {
        /* @文字消息回复格式
         *
         * <xml>
         * <ToUserName><![CDATA[toUser]]></ToUserName>
         * <FromUserName><![CDATA[fromUser]]></FromUserName>
         * <CreateTime>12345678</CreateTime>
         * <MsgType><![CDATA[text]]></MsgType>
         * <Content><![CDATA[你好]]></Content>
         * </xml>
         *
         * */
        $fromUserName = $postObj->ToUserName;
        $toUserName = $postObj->FromUserName;
        $template = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[%s]]></MsgType>
                        <Content><![CDATA[%s]]></Content>
                    </xml>";
        return sprintf($template, $toUserName, $fromUserName, time(), 'text', $content);
    }

    /*
     * 生产二维码
     */

    public function Text($postObj)
    {
        return $this->responseText($postObj, '欢迎关注速用科技！该服务号正在开发中...');
    }

    /*
     *  文本回复事件
     * $parm = XML As Array
     */

    public function creartQrcode($contact, $str = 'scene_str', $type = 'QR_STR_SCENE', $expire = 2592000, $isIMG = false)
    {
        $SDK = new WechatSDK(Config::get('wechat.mp_appid'), Config::get('wechat.mp_appsecret'));
        $Ticket = $SDK->getQRCodeTicket($contact, $str, $type, $expire);
        return $SDK->getQRCode($Ticket, $isIMG);
    }


    /*
     * 发送模板消息
     * DATA = {value='',color=''}
     */

    public function sendMessage_tpl($tplid, $openid, $data)
    {
        $SDK = new WechatSDK(Config::get('wechat.mp_appid'), Config::get('wechat.mp_appsecret'));
        switch ($tplid) {
            /*
             *  新订单提醒 模板ID
             *  {{first.DATA}}
             *  内容：{{keyword1.DATA}}
             *  时间：{{keyword2.DATA}}
             *  {{remark.DATA}}
             */
            case 'r4F4Ld5UP58SRjboJrj009NF08dj0ZHPtTr4sRTHb3w':
                // 新订单提醒
                $template = [
                    'touser' => $openid,
                    'template_id' => $tplid,
                    'data' => $data
                ];
                $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $SDK->getAccessToken();
                $json_template = json_encode($template, JSON_UNESCAPED_UNICODE);
                $dataRes = json_decode($SDK->_requestPost($url, $json_template), true);
                while ($dataRes['errcode'] != 0) {
                    if ($dataRes['errcode'] == -1) {
                        $dataRes = json_decode($SDK->_requestPost($url, $json_template), true);
                    } else {
                        return false;
                    }
                }
                return $dataRes; // json_decode($dataRes, true);
                break;
        }
        return false;
    }

    /*
     *  根据预授权码获取授权公众号信息
     */
    public function api_query_auth($auth_code)
    {
        $open = new Open();
        $component_access_token = json_decode($open->get_component_access_token(), true)['data']['component_access_token'];   //  获取component_access_token
        $url = 'https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=' . $component_access_token;
        $data = [
            "component_appid" => Config::get('wxopen.appid'),
            "authorization_code" => $auth_code
        ];
        $jsonstr = json_encode($data, JSON_UNESCAPED_UNICODE);
        $arr = new Base();
        $result = $arr->_requestPost($url, $jsonstr);
        $res = json_decode($result, true);
        return $res['authorization_info'];
    }

    /*
     *  获取小程序模板库标题列表
     *  {
     *   “offset”:0,
     *   “count”:5
     *  }
     */
    public function templateLibraryList($access_token = null, $data = [])
    {
        if (empty($access_token) or empty($data)) {
            return false;
        }
        $api = 'https://api.weixin.qq.com/cgi-bin/wxopen/template/library/list?access_token=' . $access_token;
        return $this->_requestPost($api, $data);
    }

    /*
     *  组合模板并添加至帐号下的个人模板库 得到 template_id
     */
    public function addTemplateMiniapp($access_token = null, $template_id = null, $keyword_id_list = [])
    {
        if (empty($template_id) or empty($keyword_id_list) or empty($access_token)) {
            return false;
        }
        $api = 'https://api.weixin.qq.com/cgi-bin/wxopen/template/add?access_token=' . $access_token;
        $res = $this->_requestPost($api, ['id' => $template_id, 'keyword_id_list' => $keyword_id_list]);
        if ($res) {
            $data = json_decode($res, true);
            if (isset($data['template_id'])) {
                return $data['template_id'];
            }
        }
        return false;
    }
}



















